﻿using System;
using System.Data;
using System.Web;
using DevExpress.Web;
using System.Web.UI;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Drawing;
using System.IO;
using OfficeOpenXml.Drawing;
using System.Net.Mail;
using System.Net;
using System.Web.SessionState;
using System.Collections.Generic;



public class Utils
{
    
    static HttpRequest Request
    {
        get
        {
            return Context.Request;
        }
    }

    static HttpResponse Response
    {
        get
        {
            return Context.Response;
        }
    }

    static HttpContext Context
    {
        get
        {
            return HttpContext.Current;
        }
    }


    public static void PostGlobalMessage(ASPxLabel InformationLabel)
    {
        InformationLabel.Text = Sessions.GlobalMessage;
        HttpContext.Current.Session["GlobalMessage"] = "";
    }



    public static string ToProperCase(string text)
    {
        string formattedText = null;

        if (text != null)
        {
            formattedText = new System.Globalization.CultureInfo("en").TextInfo.ToTitleCase(text.ToLower()).Replace("ı","i");
        }

        return formattedText;
    }


    public class PhotoColumnTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            LiteralControl lit = new LiteralControl();
            GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;

            lit.Text = Utils.PhotoColumnString(gridContainer.KeyValue);
            container.Controls.Add(lit);
        }
    }

    public class MissingPhotoColumnTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            LiteralControl lit = new LiteralControl();
            GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;

            lit.Text = Utils.PhotoColumnString(int.Parse(gridContainer.Text));
            container.Controls.Add(lit);
        }
    }

    public class AvailableQtyTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            LiteralControl lit = new LiteralControl();
            GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;
            DataRowView dataRow = (DataRowView)gridContainer.Grid.GetRow(gridContainer.VisibleIndex);
            string id = gridContainer.KeyValue.ToString();
            lit.Text = @"<span onclick=""pop('" + id + @"');"" > " + FormatAsMeterAvailable(dataRow["AvailableQty"]) + " </span>";
            container.Controls.Add(lit);
        }
    }

    public class Du4MissingQtyTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            LiteralControl lit = new LiteralControl();
            GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;
            DataRowView dataRow = (DataRowView)gridContainer.Grid.GetRow(gridContainer.VisibleIndex);
            string id = gridContainer.KeyValue.ToString();
            lit.Text = @"<span style=""text-docaration:underline"" onclick=""doCallBack('" + id + @"');"" > " + FormatAsMeterAvailable(dataRow["MissingQty"]) + " </span>";
            container.Controls.Add(lit);
        }
    }

    public class QtyInStockTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            LiteralControl lit = new LiteralControl();
            GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;
            DataRowView dataRow = (DataRowView)gridContainer.Grid.GetRow(gridContainer.VisibleIndex);
            string id = gridContainer.KeyValue.ToString();
            lit.Text = @"<span onclick=""pop('" + id + @"');"" > " + FormatAsMeterAvailable(dataRow["QtyInStock"]) + " </span>";
            container.Controls.Add(lit);
        }
    }

    public class QtyBlocked : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            LiteralControl lit = new LiteralControl();
            GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;
            DataRowView dataRow = (DataRowView)gridContainer.Grid.GetRow(gridContainer.VisibleIndex);
            string id = gridContainer.KeyValue.ToString();
            lit.Text = @"<span onclick=""popBlocked('" + id + @"');"" > " + FormatAsMeter(dataRow["BlockedQty"]) + " </span>";
            container.Controls.Add(lit);
        }
    }

    public class AvailableQtyReadOnlyTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            LiteralControl lit = new LiteralControl();
            GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;
            DataRowView dataRow = (DataRowView)gridContainer.Grid.GetRow(gridContainer.VisibleIndex);
            string id = gridContainer.KeyValue.ToString();
            lit.Text = @"<span onclick=""pop2('" + id + @"');"" > " + FormatAsMeterAvailable(dataRow["AvailableQty"]) + " </span>";
            container.Controls.Add(lit);
        }
    }

    public class KpiColumnTemplate : ITemplate
    {
        public void InstantiateIn(Control container)
        {
            LiteralControl lit = new LiteralControl();
            GridViewDataItemTemplateContainer gridContainer = (GridViewDataItemTemplateContainer)container;
            decimal qtyRequested = 0;
            decimal qtyBestMatch = 0;
            decimal qtyAvailable = 0;
            bool isForced = false;
            int productId = 0 ;
            DataRowView dataRow =  (DataRowView)gridContainer.Grid.GetRow(gridContainer.VisibleIndex);
             if (dataRow.Row["RequestedQty"] != DBNull.Value)
                 qtyRequested = (decimal)(dataRow.Row["RequestedQty"]);

             
            if (dataRow.Row["AvailableQty"] != DBNull.Value)
                 qtyAvailable = (decimal)(dataRow.Row["AvailableQty"]);

             if (dataRow.Row["BestMatchQty"] != DBNull.Value)
                 qtyBestMatch = (decimal)(dataRow.Row["BestMatchQty"]);

             if (dataRow.Row["ProductId"] != DBNull.Value)
                 productId = (int)(dataRow.Row["ProductId"]);

             if (dataRow.Row["isForced"] != DBNull.Value)
                 isForced = (bool)(dataRow.Row["isForced"]);

             lit.Text = Utils.KpiColumnString(qtyRequested, qtyBestMatch,qtyAvailable, productId,isForced);
            container.Controls.Add(lit);
        }
    }

    public static string devxPhotoColumnString(object ProductId)
    {
        //return "";
        int productId = (int)ProductId;
        
         string events = String.Format(@" onmouseout=""closeBigimg();"" onmouseover=""bigimg('{0}','Article Scan');""", productId);
            
        string td = String.Format(@"<TD valign='middle'>
            <img width=""32"" id=""sa{0}"" height=""32"" style=""cursor:pointer"" src=""../images/articles/s_{0}.png"" {1} ></TD>", productId, events);

        string row = string.Format( @"<table cellpadding='0' cellspacing='0'><tr>{0}</tr></table>", td);
        return row;
    }

    public static string PhotoColumnString(object ProductId)
    {
        string srcSmall = string.Format("../images/articles/s_{0}.png",ProductId);
        string srcLarge = string.Format("../images/articles/l_{0}.png", ProductId);

        FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath(srcSmall));
        if (!fi.Exists) srcSmall = "../images/notready2.png";

        fi = new FileInfo(HttpContext.Current.Server.MapPath(srcLarge));
        if (!fi.Exists) srcLarge = "../images/notreadyBig.png";
        
        //return "";
        int productId = (int)ProductId;

        string td = String.Format(@"<TD valign='middle'>
            <img width=""32"" id=""sa{0}"" height=""32"" style=""cursor:pointer"" src=""{0}"" ></TD>", srcSmall);

        string row = string.Format(@"<table cellpadding='0' cellspacing='0'><tr>{0}</tr></table>", td);
        row = string.Format(@"<a onclick=""box('{0}')""> {1} </a>", srcLarge, row);
        return row;
    }

    public static string KpiColumnString(decimal qtyRequested, decimal qtyBestMatch, decimal qtyAvailable,int productId,bool isForced)
    {
        if (qtyRequested == 0) return "";
        
        decimal result = qtyBestMatch - qtyRequested;
        string imgName;
        string summary;
        string strQtyBestMatch = FormatAsMeter(qtyBestMatch);
        string strResult = FormatAsMeter(result);
        if (result == 0)
        {
            imgName = "tam";
            summary = ""  ;            
        }
        else if (result > 0)
        {
            imgName = "fazla";
            summary = "+" + strResult;       
        }
        else
        {
            imgName = "eksik";
            summary = strResult;    
        }

        string img = "";

        string checkbox = "";

        if (result == 0 )
        {
            img = string.Format(@"<img title=""Quantity To Reserve = Requested Quantity"" onclick=""pop('{1}');"" style=""cursor:pointer;""   src=""../images/kpi/{0}.png""  />", imgName, productId);
        }
        else if (result < 0 && qtyAvailable < qtyRequested)
        {
            img = string.Format(@"<img title=""Quantity To Reserve < Requested Quantity)"" onclick=""pop('{1}');"" style=""cursor:pointer;""   src=""../images/kpi/{0}.png""  />", imgName, productId);
        } 
        else
        {
            img = string.Format(@"<img title=""Quantity To Reserve > Requested Quantity)"" onclick=""pop('{1}');"" style=""cursor:pointer;""   src=""../images/kpi/{0}.png""   />", imgName, productId);

            string strChecked = @"checked=""true""";

            //if (Request.Form[String.Format("rb_{0}", productId)] == null)
            if (! isForced)            
            {
                strChecked = "";
            }

            checkbox = string.Format(@" . Don't Accept Proposed, Need Exact Qty: <td><input name=""rb_{0}"" value=""1"" type=""checkbox""  title=""Need Exact Qty"" {1}></td>", productId, strChecked);
        }

        string table = string.Format(@"<table width=""100%""><tr><td align=""left"">{0} </td><td align=""left"" width=""100%"">{1}</td><td align=""right"">{2}</td></tr></table>", img, strQtyBestMatch, checkbox);
        return table;
 
    }

    public static string MiddlePhotoColumn(object ProductId)
    {
        int productId = (int)ProductId;

        string events = String.Format(@" onmouseout=""closeBigimg();"" onmouseover=""bigimg('{0}','Article Scan');""", productId);

        string td = String.Format(@"<TD valign='middle'>
                                    <img id=""sa{0}"" style=""cursor:pointer"" src=""../images/articles/s_{0}.png"" {1} ></TD>", productId, events);
            //<img id=""sa{0}"" style=""cursor:pointer"" src=""../images/articles/m_{0}.png"" {1} ></TD>", productId, events);
        

        string row = string.Format(@"<table cellpadding='0' cellspacing='0'><tr>{0}</tr></table>", td);
        return row;
    }


    //public static string MiddlePhotoColumnStartString(object ProductId)
    //{
    //    int productId = (int)ProductId;
    //    string events = String.Format(@" onmouseout=""closeBigimg();"" onmouseover=""bigimg('{0}','Article Scan');""", productId);

    //    string td = string.Format(@"<TD valign=""middle""> <div style=""cursor:pointer"" {0} >", events);

    //    string row = string.Format(@"<table cellpadding='0' cellspacing='0'><tr>{0}", td);
    //    return row;
    //}

    //public static string MiddlePhotoColumnEndString(object ProductId)
    //{
    //    return "</div></td></tr></table>";
    //}
     

    public static string FormatAsMeter(object val)
    {
        if (val == null || val.ToString().Trim() == string.Empty || Convert.ToDouble(val.ToString().Trim()) == 0)
        {
            return string.Empty;
        }
        else
        {
            return ((decimal)val).ToString("#,0.0") ;
        }
    }

    public static string FormatAsMeterAvailable(object val)
    {
        if (val == null || val.ToString().Trim() == string.Empty || Convert.ToDouble(val.ToString().Trim()) == 0)
        {
            return "0,0";
        }
        else
        {
            return ((decimal)val).ToString("#,0.0");
        }
    }



    public static void DumpExcel(DataTable dataTable)
    {
        using (ExcelPackage pck = new ExcelPackage())
        {
            //Create the worksheet
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Articles");

            if (dataTable.Columns["RequestedQty"] != null )
                dataTable.Columns.Remove("RequestedQty");

            if (dataTable.Columns["BestMatchQty"] != null )
                dataTable.Columns.Remove("BestMatchQty");

            if (dataTable.Columns["isForced"] != null)
                dataTable.Columns.Remove("isForced");


            //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
            ws.Cells["A1"].LoadFromDataTable(dataTable, true);

            string[] letters = new string[31] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF" };
            //Format the header for column 1-3
            using (ExcelRange rng = ws.Cells["A1:" + letters[dataTable.Columns.Count - 1] + "1"])
            {
                rng.Style.Font.Bold = true;
                rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
                rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(0x21, 0x4A, 0x7C));
                rng.Style.Font.Color.SetColor(Color.White);
            }
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                ws.Column(i + 1).AutoFit();
                string columnName = dataTable.Columns[i].Caption.ToLower();
                if (columnName.Contains("qty") || columnName.Contains("quantity"))
                {
                    using (ExcelRange col = ws.Cells[1, i + 1, dataTable.Rows.Count + 1, i + 1])
                    {
                        col.Style.Numberformat.Format = "#,#0.0";
                        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                    }
                }
            }

            ws.defaultRowHeight = 35;
            ws.Column(1).Width = 7;
            if (dataTable.Columns["ProductId"] != null)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    try
                    {


                        string productId = dataTable.Rows[i]["ProductId"].ToString();
                        string path = Context.Server.MapPath(String.Format("~/images/articles/s_{0}.png", productId));
                        FileInfo fi = new FileInfo(path);
                        //byte[] bytes = (byte[])DataAccess.GetPhoto(int.Parse(productId),"s")["Photo"];
                        //MemoryStream stream = new MemoryStream(bytes);
                        //Bitmap image = new Bitmap(stream);
                        if (!fi.Exists)
                        {
                            path = Context.Server.MapPath("~/images/notready.png");
                        }
                        Bitmap image = new Bitmap(path);
                        ExcelPicture picture = null;
                        picture = ws.Drawings.AddPicture(String.Format("pic{0}0", i + 1), image);
                        picture.SetPosition((i + 1), 10, 0, 10);
                        picture.SetSize(32, 32);

                        ws.SetValue(i + 2, 1, "");
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            //Write it back to the client
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", string.Format("attachment;  filename={0}", "ConfExpertStock_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx"));
            Response.BinaryWrite(pck.GetAsByteArray());
        }
    }
}
